home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Subject: Re: mixing enums and inte
- X-Nntp-Posting-Host: golden.ripco.com
- Message-ID: <DKpKrF.A2M@rci.ripco.com>
- Sender: usenet@rci.ripco.com (Net News Admin)
- Organization: Ripco Internet BBS Chicago
- Date: Fri, 5 Jan 1996 12:45:15 GMT
- X-Ident-Sender: mambuhl
-
- glynis@yrkpa.kias.com (John Flinchbaugh) in <4cij6k$dvb@yrkpa.kias.com>
- asks:
-
- >the faq states that mixing enums and ints is legal, but poor style.
-
- The main problem is that an enumeration constant is only guaranteed to
- be an integer. Note that "integer" does not mean an int. It could be
- any of char, short, int, or long. The standard specifies that
- "implementation-defined behavior" includes "The integer type chosen to
- represent the values of an enumeration type."
-
- Any where mixing an int with a short, char, or long could cause a problem, it is
- conceivable that a problem could arise mixing ints and enums.
-
- Another stylistic point is that you may want to rigorously treat enums
- as distinct from another type. In fact, each distinct enumeration
- _does_ represent a different enumerated type.
-
- >i'd like to use enums to organize my constants, like this:
-
- > enum DIRECT {UP=72,LEFT=75,RIGHT=77,DOWN=80};
- > int key;
- > getch(); /* dos code to get the second byte of 2-byte */
- > key=getch(); /* key codes from keyboard */
- > if (key==UP) printf("up");
- > ...
-
- >now this should work, but it's poor style, right?
-
- Since you use the non-standard function getch(), you can't be concerned
- with portability. Since, for implementation-defined behavior, "Each
- implementation shall document its behavior...", you can check your
- documentation to be sure that enums and ints mix without a problem.
- Just don't expect any implementation-defined behavior (including
- non-standard functions) to be portable, even to the next version of your
- compiler.
-
- >would casting it be more proper:
-
- > if ((enum DIRECT) key==up) ...
- ^^
- You meant UP, didn't you?
-
- >also, can you typedef enums? if so, how?
-
- typedef enum {UP=72, LEFT=75, RIGHT=77, DOWN=80} DIRECT;
-
- DIRECT which_way, last_way;
- /* ... */
- last_way = which_way;
- which_way = UP;
- if (last_way == which_way) { /* foo */ }
-
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-